<template>
  <BasicForm @register="registerForm">
    <template #autoCommit="{ model, field }">
      <div v-if="empty">
        <div v-for="(item, index) in model[field]" :key="index" class="table-box">
          <Table>
            <tr>
              <td class="py-2 px-4 w-48">
                <Select style="width: 100%" v-model:value="item.entityType" :options="entityType" />
              </td>
              <td class="py-2 px-4 w-48">
                <Select
                  style="width: 100%"
                  v-model:value="item.branch"
                  :options="branchesOptions"
                />
              </td>
              <td class="py-2 px-4 w-48" v-if="item.entityType === 'DEVICE'"> </td>
              <td class="py-2 px-4" rowspan="2">
                <Tooltip title="Remove mapping entry" class="pl-4">
                  <Icon
                    :icon="ICON.DELETE"
                    :size="20"
                    class="cursor-pointer"
                    @click="deleteRow(index)"
                  />
                </Tooltip>
              </td>
            </tr>
            <tr>
              <td class="py-2 px-4 w-48">
                <Checkbox style="width: 100%" v-model:checked="item.saveAttributes">
                  导出属性
                </Checkbox>
              </td>
              <td class="py-2 px-4 w-48">
                <Checkbox style="width: 100%" v-model:checked="item.saveRelations"
                  >导出关联</Checkbox
                >
              </td>
              <td class="py-2 px-4 w-48" v-if="item.entityType === 'DEVICE'">
                <Checkbox style="width: 100%" v-model:checked="item.saveCredentials">
                  导出凭证
                </Checkbox>
              </td>
            </tr>
          </Table>
        </div>
      </div>
      <div v-else class="p-4 w-144 text-center font-bold text-gray-400">没有设置自动提交的实体</div>
      <Button type="primary" :disabled="readonly" @click="addRow">添加实体类型</Button>
    </template>
  </BasicForm>
  <div class="h-16 bg-white w-full flex justify-end items-center mt-4">
    <Button
      v-if="isExists"
      class="mr-2"
      type="primary"
      danger
      :loading="loading"
      @click="handleDelete"
      >删除</Button
    >
    <Button
      class="mr-2"
      type="primary"
      :disabled="readonly || !empty"
      :loading="loading"
      @click="handleSave"
    >
      保存
    </Button>
  </div>
</template>

<script lang="ts" setup>
  import { BasicForm, useForm } from '/@/components/Form';
  import { autoCommitSchemas, entityType } from './setting.data';
  import Icon from '/@/components/Icon';
  import { ICON } from '/@/enums/iconEnum';
  import { Button, Select, Checkbox } from 'ant-design-vue';
  import { computed, onMounted, ref } from 'vue';
  import {
    getAutoCommitSettings,
    getRepositoryInfo,
    saveAutoCommitSettings,
    deleteAutoCommitSettings,
    exists,
  } from '/@/api/thingsborad/settings/settings';
  import { getBranches } from '/@/api/thingsborad/advanced/versionControl/versionControl';
  import { useMessage } from '/@/hooks/web/useMessage';

  type Item = {
    entityType: string;
    branch: string;
    saveAttributes: boolean;
    saveCredentials: boolean;
    saveRelations: boolean;
  };

  const list = ref<Item[]>([]);
  const branchesOptions = ref([]);
  const loading = ref<boolean>(false);
  const readonly = ref<boolean>(false);
  const isExists = ref<boolean>(false);
  const empty = computed(() => {
    return list.value.length > 0;
  });
  const { createConfirm, createMessage } = useMessage();

  const [registerForm, { setFieldsValue, validate }] = useForm({
    layout: 'vertical',
    schemas: autoCommitSchemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
  });

  const addRow = () => {
    list.value.push({
      entityType: 'DEVICE',
      branch: 'main',
      saveAttributes: true,
      saveCredentials: true,
      saveRelations: false,
    });
    console.log(list.value);
  };

  const deleteRow = (index: number | string) => {
    list.value.splice(Number(index), 1);
  };

  const handleDelete = () => {
    createConfirm({
      iconType: 'warning',
      title: '确定要删除自动提交设置吗？',
      content: '请注意：确认后，自动提交设置将被删除，所有实体的自动提交将被禁用。',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        loading.value = true;
        try {
          deleteAutoCommitSettings().then(() => {
            list.value = [];
            createMessage.success('删除成功');
          });
        } finally {
          loading.value = false;
        }
      },
    });
  };

  const handleSave = async () => {
    loading.value = true;
    try {
      const data = await validate();
      const obj = {};
      data.autoCommit.length > 0 &&
        data.autoCommit.forEach((item: Recordable) => {
          obj[item.entityType] = {
            branch: item.branch,
            saveAttributes: item.saveAttributes,
            saveCredentials: item.saveCredentials,
            saveRelations: item.saveRelations,
          };
        });
      saveAutoCommitSettings(obj).then(() => {
        createMessage.success('保存成功');
      });
    } finally {
      loading.value = false;
    }
  };

  const initBranchesOptions = () => {
    getBranches().then((res) => {
      branchesOptions.value = res.map((item: Recordable) => {
        return {
          label: item.name,
          value: item.name,
        };
      });
    });
  };

  const initAutoCommitSettings = () => {
    getAutoCommitSettings().then((res) => {
      Object.keys(res).forEach((key) => {
        list.value.push({
          entityType: key,
          branch: res[key].branch || 'main',
          saveAttributes: res[key].saveAttributes,
          saveCredentials: res[key].saveCredentials,
          saveRelations: res[key].saveRelations,
        });
      });
    });
  };

  // 判断是否已存在设置
  const checkExist = async () => {
    isExists.value = await exists();
    if (!isExists.value) return;
    initAutoCommitSettings();
  };

  // 判断仓库是否只读
  const checkReadOnly = () => {
    getRepositoryInfo().then((res) => {
      readonly.value = res.readOnly;
    });
  };

  onMounted(() => {
    setFieldsValue({
      autoCommit: list.value,
    });
    initBranchesOptions();
    checkReadOnly();
    checkExist();
  });
</script>

<style lang="less" scoped>
  .table-box {
    border: 1px solid;
    padding: 10px;
    border-radius: 8px;
    margin-bottom: 10px;
  }
</style>
